const Food = require('../models/Food');
const FoodGI = require('../models/FoodGI');
const { getNutrientInfo, convertToFoodModel } = require('../utils/tianapiUtils');
const { getOptimizedNutrientInfo } = require('../utils/tianapiUtils');
const nutritionUtils = require('../utils/nutritionUtils');
const DietMeal = require('../models/DietMeal');
const User = require('../models/User');

// 搜索食物 - 优先使用天行API
exports.searchFoods = async (req, res) => {
  try {
    const { query, category } = req.query;
    
    // 如果没有搜索关键词，返回空结果
    if (!query || !query.trim()) {
      return res.status(200).json({
        success: true,
        count: 0,
        data: []
      });
    }
    
    // 先调用天行API搜索
    let apiResponse = null;
    try {
      apiResponse = await getNutrientInfo(query, 0, 10, 1);
    } catch (error) {
      console.error('天行API搜索失败:', error);
      // API搜索失败时继续使用本地数据库搜索
    }
    
    // 构建本地数据库查询条件
    const searchQuery = {};
    
    // 使用正则表达式进行模糊匹配，增强搜索灵活性
    if (query && query.trim()) {
      searchQuery.name = { $regex: query, $options: 'i' }; // i表示不区分大小写
    }
    
    // 如果指定了分类，添加分类过滤
    if (category) {
      searchQuery.category = category;
    }
    
    // 从本地数据库查询
    const localFoods = await Food.find(searchQuery)
      .sort({ name: 1 })
      .limit(20);
    
    // 合并结果
    let combinedResults = [...localFoods];
    
    // 如果API调用成功，添加API结果
    if (apiResponse && apiResponse.success) {
      let apiResults = [];
      
      // 处理API响应数据
      if (Array.isArray(apiResponse.data)) {
        apiResults = apiResponse.data.map(item => convertToFoodModel(item));
      } else if (apiResponse.data && typeof apiResponse.data === 'object') {
        apiResults = [convertToFoodModel(apiResponse.data)];
      }
      
      // 过滤掉本地数据库中已有的食物
      const localFoodNames = new Set(localFoods.map(food => food.name));
      const uniqueApiResults = apiResults.filter(food => !localFoodNames.has(food.name));
      
      // 合并结果
      combinedResults = [...localFoods, ...uniqueApiResults];
    }
    
    res.status(200).json({
      success: true,
      count: combinedResults.length,
      data: combinedResults,
      source: apiResponse && apiResponse.success ? 'mixed' : 'local'
    });
  } catch (error) {
    console.error('搜索食物失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索食物失败',
      error: error.message
    });
  }
};

// 获取推荐食物 - 精准营养推荐版本
exports.getRecommendedFood = async (req, res) => {
  try {
    const { date = new Date().toISOString().split('T')[0] } = req.query;
    const userId = req.user._id;
    
    console.log(`获取食物推荐 - 用户: ${userId}, 日期: ${date}`);
    
    // 1. 获取用户的营养目标
    const user = await User.findById(userId);
    if (!user || !user.nutritionTarget) {
      return res.status(400).json({
        success: false,
        message: '未找到用户营养目标'
      });
    }
    
    // 2. 获取用户当日已摄入的营养素
    const todayMeals = await DietMeal.find({
      userId: userId,
      date: {
        $gte: new Date(`${date}T00:00:00.000Z`),
        $lte: new Date(`${date}T23:59:59.999Z`)
      }
    });
    
    // 3. 计算已摄入的营养总量
    const currentIntake = todayMeals.reduce((total, meal) => {
      total.calories += meal.totalCalories || 0;
      total.carbs += meal.totalCarbs || 0;
      total.protein += meal.totalProtein || 0;
      total.fat += meal.totalFat || 0;
      // 膳食纤维通常不在餐食总量中跟踪，此处估算
      total.fiber += meal.totalFiber || 0;
      return total;
    }, { calories: 0, carbs: 0, protein: 0, fat: 0, fiber: 0 });
    
    console.log('当前营养摄入情况:', currentIntake);
    
    // 4. 计算营养素缺口
    const nutritionDeficit = nutritionUtils.calculateNutritionDeficit(
      user.nutritionTarget,
      currentIntake
    );
    
    console.log('营养素缺口:', nutritionDeficit);
    
    // 5. 准备存储分类食物的对象
    const recommendations = {
      stapleRecommendations: [],
      proteinRecommendations: [],
      vegetableRecommendations: []
    };
    
    // 6. 主食推荐 - 基于GI值和碳水缺口
    if (nutritionDeficit.carbs > 0) {
      // 查询条件：主食类食物，优先低GI
      const stapleQuery = { 
        category: { $in: ['grains', 'tubers', 'legumes'] },
        isStapleFood: true
      };
      
      // 获取低GI和中GI值主食
      const lowGIStaples = await FoodGI.find({
        ...stapleQuery,
        giValue: { $lte: 55 }
      }).sort({ giValue: 1 }).limit(3);
      
      const mediumGIStaples = await FoodGI.find({
        ...stapleQuery,
        giValue: { $gt: 55, $lte: 69 }
      }).sort({ giValue: 1 }).limit(2);
      
      // 处理主食推荐数据，添加推荐份量和理由
      const processedStaples = [...lowGIStaples, ...mediumGIStaples].map(food => {
        // 计算推荐份量
        const portionInfo = nutritionUtils.calculateRecommendedPortion(
          food,
          nutritionDeficit,
          'carbs'
        );
        
        // 生成推荐标签
        const tags = nutritionUtils.generateFoodTags(food, food.giValue);
        
        // 生成推荐理由
        const reasons = nutritionUtils.generateRecommendationReasons(
          food,
          nutritionDeficit,
          food.giValue
        );
        
        return {
          ...food.toObject(),
          recommendedPortion: portionInfo.recommendedPortion,
          providedNutrition: portionInfo.providedNutrition,
          percentOfDeficit: portionInfo.percentOfDeficit,
          tags,
          reasons
        };
      });
      
      recommendations.stapleRecommendations = processedStaples;
    }
    
    // 7. 蛋白质食物推荐 - 基于蛋白质缺口
    if (nutritionDeficit.protein > 0) {
      // 本地数据库查询
      const localProteinFoods = await FoodGI.find({
        category: 'protein'
      }).sort({ 'nutrition.protein': -1 }).limit(3);
      
      // 优化处理本地数据
      const processedProteinFoods = localProteinFoods.map(food => {
        // 计算推荐份量
        const portionInfo = nutritionUtils.calculateRecommendedPortion(
          food,
          nutritionDeficit,
          'protein'
        );
        
        // 生成推荐标签和理由
        const tags = nutritionUtils.generateFoodTags(food);
        const reasons = nutritionUtils.generateRecommendationReasons(food, nutritionDeficit);
        
        return {
          ...food.toObject(),
          recommendedPortion: portionInfo.recommendedPortion,
          providedNutrition: portionInfo.providedNutrition,
          percentOfDeficit: portionInfo.percentOfDeficit,
          tags,
          reasons
        };
      });
      
      // 如果本地数据不足，尝试从API获取补充
      if (processedProteinFoods.length < 3) {
        try {
          // 从天行API获取高蛋白食物
          const apiProteinFoods = await getOptimizedNutrientInfo('蛋白质', 3, 'protein', 5);
          
          // 过滤和处理API数据
          const processedApiFoods = apiProteinFoods
            .filter(food => {
              // 确保不是重复的食物
              return !processedProteinFoods.some(
                localFood => localFood.name === food.name
              );
            })
            .map(food => {
              // 转换为标准格式
              const standardFood = {
                name: food.name,
                nutrition: {
                  protein: parseFloat(food.nutrition.protein) || 0,
                  fat: parseFloat(food.nutrition.fat) || 0,
                  calories: parseFloat(food.nutrition.calories) || 0,
                  carbs: parseFloat(food.nutrition.carbohydrate) || 0,
                  fiber: parseFloat(food.nutrition.fiber) || 0
                },
                category: 'protein',
                source: 'api'
              };
              
              // 计算推荐份量
              const portionInfo = nutritionUtils.calculateRecommendedPortion(
                standardFood,
                nutritionDeficit,
                'protein'
              );
              
              // 生成标签和推荐理由
              const tags = nutritionUtils.generateFoodTags(standardFood);
              const reasons = nutritionUtils.generateRecommendationReasons(
                standardFood,
                nutritionDeficit
              );
              
              return {
                ...standardFood,
                recommendedPortion: portionInfo.recommendedPortion,
                providedNutrition: portionInfo.providedNutrition,
                percentOfDeficit: portionInfo.percentOfDeficit,
                tags,
                reasons
              };
            });
          
          // 合并本地和API数据
          recommendations.proteinRecommendations = [
            ...processedProteinFoods,
            ...processedApiFoods
          ].slice(0, 5); // 限制最多5个推荐
        } catch (error) {
          console.error('获取API蛋白质食物失败:', error);
          recommendations.proteinRecommendations = processedProteinFoods;
        }
      } else {
        recommendations.proteinRecommendations = processedProteinFoods;
      }
    }
    
    // 8. 蔬菜推荐 - 基于纤维缺口和营养均衡
    // 本地数据库蔬菜
    const localVegetables = await FoodGI.find({
      category: 'vegetables'
    }).sort({ 'nutrition.fiber': -1 }).limit(3);
    
    // 处理本地蔬菜数据
    const processedVegetables = localVegetables.map(food => {
      // 计算推荐份量
      const portionInfo = nutritionUtils.calculateRecommendedPortion(
        food,
        nutritionDeficit,
        'fiber'
      );
      
      // 生成标签和推荐理由
      const tags = nutritionUtils.generateFoodTags(food);
      const reasons = nutritionUtils.generateRecommendationReasons(food, nutritionDeficit);
      
      return {
        ...food.toObject(),
        recommendedPortion: portionInfo.recommendedPortion,
        providedNutrition: portionInfo.providedNutrition,
        percentOfDeficit: portionInfo.percentOfDeficit,
        tags,
        reasons
      };
    });
    
    // 如果本地数据不足，尝试从API获取补充
    if (processedVegetables.length < 3) {
      try {
        // 从天行API获取蔬菜
        const apiVegetables = await getOptimizedNutrientInfo('蔬菜', 0, null, 5);
        
        // 过滤和处理API数据
        const processedApiVegetables = apiVegetables
          .filter(food => {
            return food.category === '蔬菜' && 
              !processedVegetables.some(localVeg => localVeg.name === food.name);
          })
          .map(food => {
            // 转换为标准格式
            const standardFood = {
              name: food.name,
              nutrition: {
                protein: parseFloat(food.nutrition.protein) || 0,
                fat: parseFloat(food.nutrition.fat) || 0,
                calories: parseFloat(food.nutrition.calories) || 0,
                carbs: parseFloat(food.nutrition.carbohydrate) || 0,
                fiber: parseFloat(food.nutrition.fiber) || 0
              },
              category: 'vegetables',
              source: 'api'
            };
            
            // 计算推荐份量
            const portionInfo = nutritionUtils.calculateRecommendedPortion(
              standardFood,
              nutritionDeficit,
              'fiber'
            );
            
            // 生成标签和推荐理由
            const tags = nutritionUtils.generateFoodTags(standardFood);
            const reasons = nutritionUtils.generateRecommendationReasons(
              standardFood,
              nutritionDeficit
            );
            
            return {
              ...standardFood,
              recommendedPortion: portionInfo.recommendedPortion,
              providedNutrition: portionInfo.providedNutrition,
              percentOfDeficit: portionInfo.percentOfDeficit,
              tags,
              reasons
            };
          });
        
        // 合并本地和API数据
        recommendations.vegetableRecommendations = [
          ...processedVegetables,
          ...processedApiVegetables
        ].slice(0, 5); // 限制最多5个推荐
      } catch (error) {
        console.error('获取API蔬菜数据失败:', error);
        recommendations.vegetableRecommendations = processedVegetables;
      }
    } else {
      recommendations.vegetableRecommendations = processedVegetables;
    }
    
    // 9. 生成饮食建议
    const dietarySuggestions = nutritionUtils.generateDietarySuggestions(nutritionDeficit);
    
    // 10. 检查是否有推荐数据
    const hasRecommendations = 
      recommendations.stapleRecommendations.length > 0 || 
      recommendations.proteinRecommendations.length > 0 || 
      recommendations.vegetableRecommendations.length > 0;
    
    if (!hasRecommendations) {
      console.log('没有找到符合条件的食物推荐');
      
      // 如果没有推荐，返回默认数据
      return res.status(200).json({
        success: false,
        message: '未找到符合条件的食物推荐',
        data: {
          stapleRecommendations: [],
          proteinRecommendations: [],
          vegetableRecommendations: [],
          nutritionDeficit: {},
          suggestions: []
        }
      });
    }
    
    console.log(`成功查询到推荐食物: 主食${recommendations.stapleRecommendations.length}个, 蛋白质${recommendations.proteinRecommendations.length}个, 蔬菜${recommendations.vegetableRecommendations.length}个`);
    
    // 返回最终结果
    res.status(200).json({
      success: true,
      data: {
        ...recommendations,
        nutritionDeficit,
        suggestions: dietarySuggestions,
        date
      }
    });
  } catch (error) {
    console.error('获取推荐食物失败:', error);
    res.status(500).json({
      success: false,
      message: '获取推荐食物失败',
      error: error.message
    });
  }
};

// 获取食物分类列表
exports.getFoodCategories = async (req, res) => {
  try {
    // 从数据库中获取所有不同的食物分类
    const categories = await Food.distinct('category');
    
    // 过滤掉空值并排序
    const validCategories = categories
      .filter(category => category && category.trim())
      .sort();
    
    res.status(200).json({
      success: true,
      count: validCategories.length,
      data: validCategories
    });
  } catch (error) {
    console.error('获取食物分类失败:', error);
    res.status(500).json({
      success: false,
      message: '获取食物分类失败',
      error: error.message
    });
  }
};

// 获取单个食物详情
exports.getFoodById = async (req, res) => {
  try {
    const food = await Food.findById(req.params.id);
    
    if (!food) {
      return res.status(404).json({
        success: false,
        message: '未找到该食物'
      });
    }
    
    res.status(200).json({
      success: true,
      data: food
    });
  } catch (error) {
    console.error('获取食物详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取食物详情失败',
      error: error.message
    });
  }
};

// 添加自定义食物
exports.addCustomFood = async (req, res) => {
  try {
    const { name, calories, carbs, protein, fat, fiber, sugar, category, imageUrl } = req.body;
    const userId = req.user._id;
    
    // 验证必需字段
    if (!name || !calories) {
      return res.status(400).json({
        success: false,
        message: '食物名称和卡路里是必需的'
      });
    }
    
    // 创建新食物
    const food = new Food({
      name,
      calories,
      carbs: carbs || 0,
      protein: protein || 0,
      fat: fat || 0,
      fiber: fiber || 0,
      sugar: sugar || 0,
      category: category || '自定义',
      // 图片URL为可选字段，仅用于后台管理
      ...(imageUrl && { imageUrl }),
      isVerified: false,
      source: 'user',
      createdBy: userId
    });
    
    await food.save();
    
    res.status(201).json({
      success: true,
      message: '成功添加自定义食物',
      data: food
    });
  } catch (error) {
    console.error('添加自定义食物失败:', error);
    res.status(500).json({
      success: false,
      message: '添加自定义食物失败',
      error: error.message
    });
  }
};

// 初始化常见食物数据，只在首次启动应用时调用
exports.initializeCommonFoods = async () => {
  try {
    // 检查数据库是否已有食物数据
    const count = await Food.countDocuments();
    if (count > 0) {
      console.log('食物数据库已初始化，包含 ' + count + ' 条记录');
      return;
    }
    
    // 不再预设食物数据，仅记录日志
    console.log('食物数据库未初始化，将通过天行API获取食物数据');
  } catch (error) {
    console.error('检查食物数据库状态失败:', error);
  }
};

// 使用天行API搜索食物营养信息
exports.searchTianapiFood = async (req, res) => {
  try {
    const { query, mode = 0, num = 10, page = 1 } = req.query;
    
    console.log(`处理天行API食物搜索请求 - 关键词: "${query}", 模式: ${mode}, 条数: ${num}, 页码: ${page}`);
    
    if (!query || !query.trim()) {
      return res.status(400).json({
        success: false,
        message: '搜索关键词不能为空'
      });
    }
    
    // 查询模式转为数字类型
    const searchMode = parseInt(mode);
    
    // 先检查本地数据库是否有匹配的食物
    console.log(`开始查询本地数据库 - 关键词: "${query}"`);
    let localResults = [];
    if (searchMode === 0) { // 如果是按食物名称搜索
      // 使用正则表达式进行模糊匹配
      localResults = await Food.find({ 
        name: { $regex: query, $options: 'i' } 
      })
      .sort({ name: 1 })
      .limit(5);
      
      console.log(`本地数据库查询结果: ${localResults.length} 条`);
    }
    
    // 调用天行API获取食物营养信息
    console.log(`开始调用天行API - 关键词: "${query}"`);
    const apiResponse = await getNutrientInfo(query, searchMode, num, page);
    
    console.log('天行API响应:', JSON.stringify(apiResponse));
    
    if (!apiResponse.success) {
      // 如果API请求失败但有本地结果，仍返回本地结果
      if (localResults.length > 0) {
        console.log(`天行API请求失败，返回本地数据库的结果: ${localResults.length} 条`);
        return res.status(200).json({
          success: true,
          source: 'local',
          count: localResults.length,
          data: localResults,
          message: '使用本地数据库的结果，天行API请求失败'
        });
      }
      
      // 否则返回API错误
      console.log(`天行API请求失败，无本地结果，返回错误信息: ${apiResponse.message}`);
      return res.status(500).json({
        success: false,
        message: apiResponse.message || '获取食物营养信息失败'
      });
    }
    
    // 转换返回的数据
    let results = [];
    
    // 如果apiResponse.data是数组，则处理多个结果
    if (Array.isArray(apiResponse.data)) {
      console.log(`处理天行API返回的数组数据: ${apiResponse.data.length} 条`);
      results = apiResponse.data.map(item => convertToFoodModel(item));
    } 
    // 如果是单个对象，则直接转换
    else if (apiResponse.data && typeof apiResponse.data === 'object') {
      console.log('处理天行API返回的单个对象数据');
      results = [convertToFoodModel(apiResponse.data)];
    }
    // 处理空数据或未识别格式
    else {
      console.warn(`天行API返回的数据格式无法识别: ${typeof apiResponse.data}`);
      results = [];
    }
    
    // 合并本地结果和API结果
    const combinedResults = [...localResults];
    
    // 避免重复添加已存在于本地数据库的食物
    const localFoodNames = new Set(localResults.map(food => food.name));
    
    // 计数添加了多少个API结果
    let addedCount = 0;
    
    results.forEach(food => {
      // 只添加有效名称的食物并避免重复
      if (food.name && !localFoodNames.has(food.name)) {
        combinedResults.push(food);
        addedCount++;
      }
    });
    
    console.log(`最终合并结果: 本地${localResults.length}条 + API新增${addedCount}条 = 共${combinedResults.length}条`);
    
    res.status(200).json({
      success: true,
      source: combinedResults.length > localResults.length ? 'mixed' : 'local',
      count: combinedResults.length,
      data: combinedResults
    });
  } catch (error) {
    console.error('搜索食物营养信息失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索食物营养信息失败',
      error: error.message
    });
  }
};

// 保存天行API返回的食物到本地数据库
exports.saveTianapiFood = async (req, res) => {
  try {
    const { foodData } = req.body;
    
    if (!foodData) {
      return res.status(400).json({
        success: false,
        message: '未提供食物数据'
      });
    }
    
    // 查询是否已存在具有相同名称的食物
    const existingFood = await Food.findOne({ name: foodData.name });
    if (existingFood) {
      return res.status(200).json({
        success: true,
        message: '食物已存在',
        data: existingFood
      });
    }
    
    // 添加用户ID
    foodData.userId = req.user._id;
    
    // 创建新的食物记录
    const newFood = new Food(foodData);
    await newFood.save();
    
    res.status(200).json({
      success: true,
      message: '保存成功',
      data: newFood
    });
  } catch (error) {
    console.error('保存天行API食物失败:', error);
    res.status(500).json({
      success: false,
      message: '保存食物失败',
      error: error.message
    });
  }
}; 